package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.adapter.FavoriteListAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.CollectionListBean;
import com.elinkway.infinitemovies.bean.Favorite;
import com.elinkway.infinitemovies.bean.UploadCollectionBean;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.RealDataApi;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.FavoriteDao;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.requestInterface.RequestCommonInterface;
import com.elinkway.infinitemovies.http.requesttask.RequestAddAllFavoriteTask;
import com.elinkway.infinitemovies.http.requesttask.RequestAlbumInfoTask;
import com.elinkway.infinitemovies.http.requesttask.RequestGetFavoriteListTask;
import com.elinkway.infinitemovies.listener.MyOnRefreshListner;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.view.PublicLoadLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.le123.ysdq.R;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FavoriteActivity extends BaseSecondaryActivity implements OnClickListener, RequestCommonInterface {

	public static final String TAG = "FavoriteActivity";
	private PullToRefreshListView list;
	private FavoriteListAdapter mAdapter;
	private FavoriteDao favoriteDao;
	private List<Favorite> favoriteList = new ArrayList<Favorite>();
	private LinearLayout noData;
	private LinearLayout editLayout;
	private TextView allSelect;
	private TextView mConfirm_delete;
	private boolean isShowButtom;
	private PublicLoadLayout root;

	private RequestGetFavoriteListTask mRequestGetFavoriteListTask;
	private SharedPreferences mLoginSp;
	private int index = 0;	//分页请求的第一个索引
	private static final int LIMIT = 20;	//每一页的数据数量
	private int total = 0;		//总数
	private boolean hasMore = true;
	private boolean isFirst = true;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			list.onRefreshComplete();
			super.handleMessage(msg);
		}

	};

	@Override
	public void requestSuccess(int updateId, Object data, String name) {
		root.finish();
		if(name.equals(MoviesHttpApi.GET_FAVORITE_DATA)) { //收藏列表
			total = ((CollectionListBean) data).getTotal();
			if(index == 0){
				favoriteList = ((CollectionListBean) data).getCollectionList();
			}else{
				favoriteList.addAll(((CollectionListBean) data).getCollectionList());
			}
			if(favoriteList.size()==0){
				showNoData();
			}else{
				if(index + LIMIT < total){
					index = index + LIMIT;
					resetHasMore();
				}else{
					setNoMore();
				}
				if(isShowButtom){
					mRightFirstTv.setText("完成");
					currentState = State.EDITING;
					editLayout.setVisibility(View.VISIBLE);
				}
				showList();
				mAdapter.updateData(favoriteList);
				list.onRefreshComplete();
			}
			setTitle();
		}else if(name.equals(MoviesHttpApi.ADD_FAVORITE)){
			if(0 == mAdapter.list.size()){
				index = 0;
				if (mRequestGetFavoriteListTask != null) {
					if (!mRequestGetFavoriteListTask.isCancelled()) {
						mRequestGetFavoriteListTask.cancel();
						mRequestGetFavoriteListTask = null;
					}
				}
				mRequestGetFavoriteListTask = new RequestGetFavoriteListTask(FavoriteActivity.this, index, LIMIT);
				mRequestGetFavoriteListTask.setRequestListener(FavoriteActivity.this);
				mRequestGetFavoriteListTask.start();
			}
		}

	}

	@Override
	public void requestFail(String name) {
		root.finish();
		root.error(false, false);
	}

	@Override
	public void netError(String name) {
		root.finish();
		root.error(false, false);
	}

	private enum State {
		EDITING, UNEDIT;
	}

	private State currentState = State.UNEDIT;
	
	 @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	    	switch(item.getItemId()){
	    	case R.id.edit:
	    		break;
	    	}
	        return super.onOptionsItemSelected(item);
	    }
	    
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		super.setActionBarActivityClassName(TAG);
		currentPageId = BigDataConstants.PGV_CURRENT_ID_COLLECT;
		MoviesApplication.getInstance().setLastPageClassName(TAG);
		root = UIs.createPage(this, R.layout.activity_favorite_new);
		setContentView(root);
		root.setmRefreshData(new PublicLoadLayout.RefreshData() {

			@Override
			public void refreshData() {
				root.loading(false);
				refreshFavoritePage();
			}
		});
		initActionBar();
		favoriteDao = new FavoriteDao(this);
        initView(root);
    }

	@Override
	protected void initActionBar(){
		super.initActionBar();
		mTitleTv.setText(R.string.myfavorites);
		mRightFirstIv.setVisibility(View.GONE);
		mRightSecondIv.setVisibility(View.GONE);
		mRightFirstTv.setText("编辑");
		mRightFirstTv.setVisibility(View.GONE);
		mRightFirstTv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				switch (currentState) {
					case UNEDIT:
						mAdapter.toggle();
						mRightFirstTv.setText("完成");
						currentState = State.EDITING;
						isShowButtom = true;
						editLayout.setVisibility(View.VISIBLE);
						break;
					case EDITING:
						mAdapter.toggle();
						allSelect.setText(R.string.check_all);
						mConfirm_delete.setText(R.string.delete_up);
						mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
						favoriteAllDiselected();
						mRightFirstTv.setText("编辑");
						currentState = State.UNEDIT;
						isShowButtom = false;
						editLayout.setVisibility(View.INVISIBLE);
						break;
				}
			}
		});
	}

	private void initView(View view) {
		mLoginSp = getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
		editLayout = (LinearLayout) view.findViewById(R.id.editlayout);
		allSelect = (TextView) view.findViewById(R.id.all_select);
		mConfirm_delete = (TextView) view.findViewById(R.id.confirm_delete);
		mConfirm_delete.setOnClickListener(this);
		allSelect.setOnClickListener(this);
		list = (PullToRefreshListView) view.findViewById(R.id.favorite_list);
		mAdapter = new FavoriteListAdapter(this, favoriteList);
		list.setAdapter(mAdapter);
		mAdapter.registerDataSetObserver(new DataSetObserver() {
			@Override
			public void onChanged() {
				if (mAdapter.getCount() == 0) {
					showNoData();
				}
				super.onChanged();
			}
		});
		noData = (LinearLayout) view.findViewById(R.id.favorite_no_data);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
									long arg3) {

				if (mAdapter.getEditState()) {
					mAdapter.setSelectItemChange(position - 1, view);
				} else {
					Favorite favorite = favoriteList.get(position - 1);
					favorite.setUpdate();
					favoriteDao.update(favorite);

					Map<String, String> dataMap = BigDataApi.createDataMap("0", "","0","-",favorite.getAid(),"-");
					dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_COLLECT);
					BigDataApi.bigDataCommonReport(dataMap, FavoriteActivity.this);

					RealDataApi.RealDataClickReport("","",favorite.getAid(),"","");
					VideoDetailActivity.launch(FavoriteActivity.this, favorite.getAid(), favorite.getVt(), favorite.getName(), favorite.getSrc(), "", "", "0","","");
				}
			}
		});

		resetHasMore();
		refreshFavoritePage();

	}

	private void refreshFavoritePage() {
		if(mLoginSp != null && !"".equals(mLoginSp.getString(LoginActivity.TOKEN, ""))) {
			list.setOnRefreshListener(new FavoriteOnRefreshListener());
			mRequestGetFavoriteListTask = new RequestGetFavoriteListTask(FavoriteActivity.this, index, LIMIT);
			mRequestGetFavoriteListTask.setRequestListener(this);
			mRequestGetFavoriteListTask.start();
		}else{
			List<String> noPosterFavoriteList = favoriteDao.getNoPosterAidList();
			if(noPosterFavoriteList != null && noPosterFavoriteList.size() > 0){
				new RequestAlbumInfoTask(this, noPosterFavoriteList, "favorite").start();
			}
			favoriteList=favoriteDao.getAll();
			if (favoriteList.size() == 0) {
				showNoData();
			} else {
				showList();
				setNoMore();
				mAdapter.updateData(favoriteList);
			}
		}
	}


	private void showNoData() {
		list.setVisibility(View.GONE);
		noData.setVisibility(View.VISIBLE);
		mRightFirstTv.setVisibility(View.GONE);
		editLayout.setVisibility(View.INVISIBLE);
		supportInvalidateOptionsMenu();
		isFirst = !isFirst;
	}
	private void showList(){
		list.setVisibility(View.VISIBLE);
		noData.setVisibility(View.GONE);
		mRightFirstTv.setVisibility(View.VISIBLE);
		if(isFirst){
			supportInvalidateOptionsMenu();
			isFirst = !isFirst;
		}
	}

	public static void launch(Activity activity) {
		Intent intent = new Intent(activity, FavoriteActivity.class);
		UmengEventPoster.postChannelClick(UmengEventPoster.CHANNEL_FAVOR);
		activity.startActivity(intent);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	@Override
	protected void onDestroy(){
		
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.confirm_delete:
			if (null != mAdapter) {
				if (!mAdapter.deleteState) {
					if (mAdapter.deletedNum > 0) {
						deleteTip();
						MoviesConstant.isRefreshMyFragment = true;
					}
				}
			}
			
			break;
		case R.id.all_select:
			if (mAdapter.deletedNum == mAdapter.getCount()) {
				allSelect.setText(R.string.check_all);
				mAdapter.allSelectState = false;
			} else {
				allSelect.setText(R.string.deselect_all);
				mAdapter.allSelectState = true;
			}
			favoriteAllSelected();
			mAdapter.notifyDataSetChanged();

			break;
		}
		
	}

	//删除提示
	private void deleteTip() {
		try {
			Builder builder = new Builder(this);
			builder.setTitle(R.string.tip);
			int deletingCount = mAdapter.deletedNum;
			String deleteTipContent = getString(R.string.favorite_delete_confirm,deletingCount);
			builder.setMessage(deleteTipContent);
			builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					MoviesConstant.isRefreshMyFragment = true;
					dialog.dismiss();
					favoriteSelectDelete();
				}
			});
			builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			Dialog dialog = builder.create();
			dialog.show();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//删除listview 选中数据
	private void favoriteSelectDelete(){
		MoviesConstant.isRefreshMyFragment = true;
		FavoriteDao favoriteDao = mAdapter.favoriteDao;
		List<Favorite> list = mAdapter.list;
		List<UploadCollectionBean> removeCollectionList = new ArrayList<>(); //批量删除
		ArrayList<Boolean> bools = mAdapter.mCheckedList;
		int size = bools.size();
		int deleteNum = 0;
		for (int pos = 0; pos < size; pos++) {
			if (bools.get(pos -deleteNum)) {//选中状态
				UploadCollectionBean uploadCollectionBean = new UploadCollectionBean();
				uploadCollectionBean.setAction("1");
				uploadCollectionBean.setRelatedId(list.get(pos - deleteNum).getAid());
				uploadCollectionBean.setTime(list.get(pos - deleteNum).getFavoriteTime() + "");
				uploadCollectionBean.setType("1");
				removeCollectionList.add(uploadCollectionBean);

				favoriteDao.delete(list.get(pos - deleteNum).getAid());
				list.remove(pos - deleteNum);
				if(favoriteList != null && favoriteList.size() > pos - deleteNum){
					favoriteList.remove(pos - deleteNum);
				}
				bools.remove(pos - deleteNum);
				mAdapter.deletedNum--;
				deleteNum ++;
			}
		}

		if(!"".equals(mLoginSp.getString(LoginActivity.TOKEN, ""))){
			RequestAddAllFavoriteTask mRequestAddAllFavoriteTask = new RequestAddAllFavoriteTask(FavoriteActivity.this, removeCollectionList);
			mRequestAddAllFavoriteTask.setRequestListener(FavoriteActivity.this);
			mRequestAddAllFavoriteTask.start();
		}

		mConfirm_delete.setText(R.string.delete_up);
		mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
		this.mAdapter.notifyDataSetChanged();
		
	}
	
	private void favoriteAllDiselected(){
		MoviesConstant.isRefreshMyFragment = true;
		for(int i = 0; i < mAdapter.mCheckedList.size(); i ++){
			mAdapter.mCheckedList.set(i, false);
		}
		mAdapter.deletedNum = 0;
		
	}
	private void favoriteAllSelected() {
		MoviesConstant.isRefreshMyFragment = true;
		if (mAdapter.deletedNum != mAdapter.getCount()) {
			String content = getString(R.string.delete_up) + "(" +mAdapter.getCount() + ")";
			mConfirm_delete.setText(content);
			mConfirm_delete.setTextColor(getResources().getColor(R.color.red_f9362a));
			for (int i = 0; i < mAdapter.getCount(); i++) {
					mAdapter.mCheckedList.add(i, true);
			}
			mAdapter.deletedNum = mAdapter.getCount();
		} else {

			mConfirm_delete.setText(R.string.delete_up);
			mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
			// 用户选择取消全选则用户当前选中项为0
			mAdapter.deletedNum = 0;
			for (int i = 0; i < mAdapter.mCheckedList.size(); i++) {
				mAdapter.mCheckedList.set(i, false);
			}
			mAdapter.deletedNum = 0;
		}

		
	}
	
	
	public void setTitle() {
		showUserSelecedItem(mAdapter.deletedNum);
	}
	
	private void showUserSelecedItem(int deleteNum) {
		String deleteContent = "";
		String allSelectContent = "";
		if(deleteNum != 0){//没有全部删除
			
			if(deleteNum == mAdapter.getCount()){
				allSelectContent = getString(R.string.deselect_all);
			}else{
				allSelectContent = getString(R.string.check_all);
			}
			deleteContent = getString(R.string.delete_up) + "(" + deleteNum + ")";
		}else{//全部删除
			
			deleteContent = getString(R.string.delete_up);
			allSelectContent = getString(R.string.check_all);
		}
		allSelect.setText(allSelectContent);
		mConfirm_delete.setText(deleteContent);
		mConfirm_delete.setTextColor(getResources().getColor(R.color.red_f9362a));
		mAdapter.notifyDataSetChanged();
		
	}

	private class FavoriteOnRefreshListener extends MyOnRefreshListner {

		@Override
		protected void onLoadMoreData() {
			if (hasMore) {
				if (mRequestGetFavoriteListTask != null) {
					if (!mRequestGetFavoriteListTask.isCancelled()) {
						mRequestGetFavoriteListTask.cancel();
						mRequestGetFavoriteListTask = null;
					}
				}
				mRequestGetFavoriteListTask = new RequestGetFavoriteListTask(FavoriteActivity.this, index, LIMIT);
				mRequestGetFavoriteListTask.setRequestListener(FavoriteActivity.this);
				mRequestGetFavoriteListTask.start();
			} else {
				handler.sendEmptyMessageDelayed(0, 50);
			}
		}

		@Override
		protected void onRefreshData() {
			index = 0;
			if (mRequestGetFavoriteListTask != null) {
				if (!mRequestGetFavoriteListTask.isCancelled()) {
					mRequestGetFavoriteListTask.cancel();
					mRequestGetFavoriteListTask = null;
				}
			}
			mRequestGetFavoriteListTask = new RequestGetFavoriteListTask(FavoriteActivity.this, index, LIMIT);
			mRequestGetFavoriteListTask.setRequestListener(FavoriteActivity.this);
			mRequestGetFavoriteListTask.start();
		}

	}

	private void resetHasMore() {
		hasMore = true;
		list.setLoadingDrawable(
				getResources().getDrawable(R.drawable.default_ptr_rotate),
				PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
		list.setRefreshingLabel(getString(R.string.loading),
				PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
		list.setReleaseLabel(getString(R.string.release_loadmore),
				PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
		list.setPullLabel(getString(R.string.pull_loadmore),
				PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
	}

	private void setNoMore() {
		hasMore = false;
		list.setLoadingDrawable(
				getResources().getDrawable(R.drawable.transparent),
				PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
		list.setRefreshingLabel(getString(R.string.havenomore),
				PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
		list.setReleaseLabel(getString(R.string.havenomore),
				PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
		list.setPullLabel(getString(R.string.havenomore),
				PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
	}
	
}